<?php
class ProductsController extends AppController {

	var $name = 'Products';
				
	var $helpers = array('Form','Javascript', 'Session','Html','Form','Ajax','Text');
				
	var $uses = array('User');
		function beforeFilter(){
		$this->Auth->allow(array('index','product', 'cart', 'DeptProducts', 'offer_listing', 'search', 'advancesearch', 'advancesearchresults'));
		parent::beforeFilter();
    }
	
	
	function index($category_slug="", $parent="")
		{
			$params = $this->params;
			$this->layout ="default";
			if(isset($params['named']['category_slug']) and ($params['named']['category_slug']))
				{
					$category_slug = $params['named']['category_slug'];
				}
				
			if((isset($params['named']['brand_slug']) and ($params['named']['brand_slug'])))
				{
					//echo "hji";
					//exit;
					
					$brand_id = $this->__get_slug_to__id($params['named']['brand_slug'], "Brand"); 
					$brand_name = $this->_get_brand_name($brand_id);
					$this->Set('title',$brand_name['name'] );
					
					     $products = $this->_getProducts('Product.brand_id="'.$brand_id.'" and Product.status="1"');
						 
						 
						if(isset($params['named']['category_slug']) and ($params['named']['category_slug']))
							{
								$category_slug = $params['named']['category_slug'];
								$this->set('cat_slug',$category_slug);
							}
							$cat_id  = $this->__get_slug_to__id($category_slug, "Category");
							$subcats = $this->_get_subcatecategories($cat_id, "");
							if(isset($subcats) and ($subcats))
							$this->Set('refer_categories',$subcats); 
								$c =0; 
								foreach($subcats as $subcat)
									{
										$subcats_inner_it = $this->_get_subcatecategories($subcat['Category']['id'], 4);
										if(isset($subcats_inner_it) and ($subcats_inner_it)):										
										  $subcats[$c]['Category']['subcategories'] = $subcats_inner_it; 
										endif;	
										$c++;								 
									}
						$this->Set('subcats',$subcats );
						if(isset($params['named']['parent_cat_slug']) and ($params['named']['parent_cat_slug']) or $category_slug)
							{
								//echo "hi";
								
								if(isset($params['named']['parent_cat_slug']) and ($params['named']['parent_cat_slug']))
									{
										//echo $params['named']['parent_cat_slug'];
										$Parent_cat_id  = $this->__get_slug_to__id($params['named']['parent_cat_slug'], "Category");
									}
									else
									{
										if(isset($category_slug) and ($category_slug))
											{
												$Parent_cat_id  = $this->__get_slug_to__id($category_slug, "Category");
											}
									}
								//pr($Parent_cat_id);
								//exit;
								
								$attribute_group = $this->AttrGroup->find('all', array('conditions'=>'AttrGroup.cat_id="'.$Parent_cat_id.'"'));
								if(isset($attribute_group) and ($attribute_group))
									{
										$x=0;
										foreach($attribute_group as $attribute)
											{
												
						$attributes = $this->Attribute->find('all', array('conditions'=>'Attribute.attr_gp_id="'.$attribute['AttrGroup']['id'].'"'));
						$o=0;
						foreach($attributes as $attr)
							{
								$specifications = $this->Specification->find('all', 
								array('conditions'=>'Specification.attr_id ="'.$attr['Attribute']['id'].'"',
								'fields'=>'DISTINCT Specification.value'));
								$attributes[$o]['Attribute']['specifications'] = $specifications; 
								$o++;
							}
								$attribute_group[$x]['AttrGroup']['Attributes'] = $attributes; 
								$x++;
							}
							//pr($attribute_group);
							//exit;
								$this->Set('attribute_group', $attribute_group);
									}
							}
					
					
					
					
					
					
					
				}
				
				
			else if(isset($category_slug) and ($category_slug) and ($category_slug!="cart") and (!isset($params['named']['brand_slug'])))
					{
						$cat_id  = $this->__get_slug_to__id($category_slug, "Category");
						$departments =  $this->Department->find('all', array('conditions'=>'Department.cat_id Like "%'.$cat_id.'%"')); 
						if(isset($cat_id) and ($cat_id) and sizeof($cat_id)):	
							$cats = $this->__get_details( $cat_id, "Category");
								if(isset($cats) and ($cats)):
								  $subcats = $this->_get_subcatecategories($cat_id, "");
										if(isset($subcats) and ($subcats)):
										$this->Set('refer_categories',$subcats); 
											$c =0; 
											foreach($subcats as $subcat)
												{
													$subcats_inner_it = $this->_get_subcatecategories($subcat['Category']['id'], 4);
													if(isset($subcats_inner_it) and ($subcats_inner_it)):										
													  $subcats[$c]['Category']['subcategories'] = $subcats_inner_it; 
													endif;	
													$c++;								 
												}
											$this->Set('subcats',$subcats );
										endif;
								  $brands = $this->Brand->find('all', array('conditions'=>'Brand.cat_id Like "%'.$cat_id.'%"')); 
								  //pr( $brands);
								 // exit;
									if(isset($brands) and ($brands))
										{
											$custum_brands[0] = $brands[0]; 
										}
										$this->Set('custum_brands', $custum_brands);
								  
								$this->Set('title',$cats['Category']['name'] );
								$this->Set('Category', $cats);
								$this->Set('departments',$departments); 
								endif;
							$total_products = $this->Product->find('count',array('conditions' =>
							'Product.cat_id="'.$cat_id.'" and Product.status="1"') );
							$this->Set('total_products', $total_products); 
							$conditions = '(Product.cat_id="'.$cat_id.'" or Product.parent_cat_id="'.$cat_id.'") and Product.status="1"'; 
							if(isset($params['named']['price']) and ($params['named']['price']))
								{
									$price = $params['named']['price'];
									$products = $this->_getProducts($conditions, $price );	
								}
							else
								{
									$products = $this->_getProducts($conditions,"");	
								}
						endif;
						
						if(isset($params['named']['parent_cat_slug']) and ($params['named']['parent_cat_slug']) or $category_slug)
							{
								//echo "hi";
								
								if(isset($params['named']['parent_cat_slug']) and ($params['named']['parent_cat_slug']))
									{
										//echo $params['named']['parent_cat_slug'];
										$Parent_cat_id  = $this->__get_slug_to__id($params['named']['parent_cat_slug'], "Category");
									}
									else
									{
										if(isset($category_slug) and ($category_slug))
											{
												$Parent_cat_id  = $this->__get_slug_to__id($category_slug, "Category");
											}
									}
								//pr($Parent_cat_id);
								//exit;
								
								$attribute_group = $this->AttrGroup->find('all', array('conditions'=>'AttrGroup.cat_id="'.$Parent_cat_id.'"'));
								if(isset($attribute_group) and ($attribute_group))
									{
										$x=0;
										foreach($attribute_group as $attribute)
											{
												
						$attributes = $this->Attribute->find('all', array('conditions'=>'Attribute.attr_gp_id="'.$attribute['AttrGroup']['id'].'"'));
						$o=0;
						foreach($attributes as $attr)
							{
								$specifications = $this->Specification->find('all', 
								array('conditions'=>'Specification.attr_id ="'.$attr['Attribute']['id'].'"',
								'fields'=>'DISTINCT Specification.value'));
								$attributes[$o]['Attribute']['specifications'] = $specifications; 
								$o++;
							}
								$attribute_group[$x]['AttrGroup']['Attributes'] = $attributes; 
								$x++;
							}
							//pr($attribute_group);
							//exit;
								$this->Set('attribute_group', $attribute_group);
									}
							}
					}
			else
				{
					$total_products = $this->Product->find('count',array('conditions' => 'Product.status="1"') );
					$this->Set('total_products', $total_products); 
					$products = $this->_getProducts('Product.status="1"');	
				}
				
				
					$this->Set('products', $products);
			/* End Categories Section */
		}
		function DeptProducts($department_slug="")
		{
			$this->layout ="default";
			$params = $this->params;
			if(isset($params['named']['category_slug']) and ($params['named']['category_slug']))
				{
					$category_slug = $params['named']['category_slug'];
				}
			
			
			if(isset($params['named']['parent_cat_slug']) and ($params['named']['parent_cat_slug']) or $category_slug)
							{
								
								
								if(isset($category_slug) and ($category_slug))
									{
										$Parent_cat_id  = $this->__get_slug_to__id($category_slug, "Category");
									}
								elseif(isset($params['named']['parent_cat_slug']) and ($params['named']['parent_cat_slug']))
									{
										$Parent_cat_id  = $this->__get_slug_to__id($params['named']['parent_cat_slug'], "Category");
									}
								
								
								$attribute_group = $this->AttrGroup->find('all', array('conditions'=>'AttrGroup.cat_id="'.$Parent_cat_id.'"'));
								if(isset($attribute_group) and ($attribute_group))
									{
										$x=0;
										foreach($attribute_group as $attribute)
											{
												
						$attributes = $this->Attribute->find('all', array('conditions'=>'Attribute.attr_gp_id="'.$attribute['AttrGroup']['id'].'"'));
						$o=0;
						foreach($attributes as $attr)
							{
								$specifications = $this->Specification->find('all', 
								array('conditions'=>'Specification.attr_id ="'.$attr['Attribute']['id'].'"',
								'fields'=>'DISTINCT Specification.value'));
								$attributes[$o]['Attribute']['specifications'] = $specifications; 
								$o++;
							}
								$attribute_group[$x]['AttrGroup']['Attributes'] = $attributes; 
								$x++;
							}
								$this->Set('attribute_group', $attribute_group);
									}
							}
			$departments =  $this->Department->find('all', array('conditions'=>'Department.slug = "'.$department_slug.'"')); 
			$this->Set('departments',$departments); 
			if(isset($departments) and ($departments))
				{
					$cats = explode(', ', $departments[0]['Department']['cat_id']);
					if(isset($cats) and ($cats))
						{
							foreach($cats as $cat)
								{
									$brands = $this->Brand->find('all', array('conditions'=>'Brand.cat_id Like "%'.$cat.'%"')); 
									
									if(isset($brands) and ($brands))
										{
											$custum_brands[] = $brands[0]; 
										}
									
								}
								//pr($custum_brands);
								//exit;
								$this->Set('custum_brands', $custum_brands);
								/*$subcats = $this->_get_subcatecategories($cat_id, "");
								if(isset($subcats) and ($subcats)):
								$this->Set('refer_categories',$subcats); 
									$c =0; 
									foreach($subcats as $subcat)
										{
											$subcats_inner_it = $this->_get_subcatecategories($subcat['Category']['id'], 4);
											if(isset($subcats_inner_it) and ($subcats_inner_it)):										
											  $subcats[$c]['Category']['subcategories'] = $subcats_inner_it; 
											endif;	
											$c++;								 
										}
									//pr($subcats);
									//exit;
									$this->Set('subcats',$subcats );
								endif;								
*/						}
				}
			
			if(isset($department_slug) and ($department_slug))
				{
					$dept_id  = $this->__get_slug_to__id($department_slug, "Department");
					
					if(isset($dept_id) and ($dept_id) and sizeof($dept_id)):
						
					$dept = $this->__get_details( $dept_id, "Department");
					
					if(isset($dept) and ($dept)):
					  $this->Set('dept', $dept);
					endif;
					
					$this->paginate['Product'] =array('conditions' => 'Product.dept_id="'.$dept_id.'" and Product.status="1"',
									'limit' => 24,
									'fields' => array('Product.*') ,
									'order' => 'Product.created Desc'
								  );
					$products = $this->paginate('Product');
					if(isset($products) and ($products))
						{   $x =0;
							foreach($products as $product)
								{
									$ratings = $this->__get_product_rating($product['Product']['wisn']);
									$products[$x]['Product']['rating'] = $ratings;
									$stock_detail = $this->_get_stock_position($product['Product']['stock']);
									$products[$x]['Product']['stock_detail']= $stock_detail; 
									$MasterProduct = $this->__get_product_min_price($product['Product']['id']);
									if(isset($MasterProduct) and ($MasterProduct))
										{
											$product_condition  = $this->_get_product_condition($MasterProduct['conditions']);
											$products[$x]['Product']['condition'] = $product_condition;
											$products[$x]['Product']['MasterProduct'] = $MasterProduct;
										}
									else
										{
											unset($products[$x]);
										}
									$x++;
								}
						   $this->Set('products', $products);
						}
					endif;
				}
		}

	function product($product_slug="")
		{
			if(isset($product_slug) and ($product_slug))
					{
						$product_details = $this->Product->findBySlug($product_slug);
						if(isset($product_details) and ($product_details))
							{
								//pr($product_details);
								//exit;
								$category = $this->Category->findById($product_details['Product']['cat_id']);
								
								$product_details['Product']['category']= $category['Category']; 
								
								$stock_detail = $this->_get_stock_position($product_details['Product']['stock']);
								
								$product_details['Product']['stock_detail']= $stock_detail;
								 
								$MasterProduct = $this->__get_product_min_price($product_details['Product']['id']);
								
								$seller = $this->_get_seller($MasterProduct['seller_id']); 
								
								$MasterProduct['Seller'] = $seller['Seller']; 
								
								$product_details['Product']['MasterProduct']= $MasterProduct;
								
								$brand_name = $this->_get_brand_name($product_details['Product']['brand_id']);
								
								$product_details['Product']['Brand'] = $brand_name; 
								
								$ratings = $this->__get_product_rating($product_details['Product']['wisn']);
								
								$product_details['Product']['rating'] = $ratings;
								
								$product_price_offers = $this->__product_price_list($product_details['Product']['id']);
								
								$product_details['Product']['offers'] = $product_price_offers;
								
								/***********************************************************************************/
									/*
										* Product reviews Start here.
									*/
								$this->paginate['ProductReview'] =array('conditions' => 'ProductReview.wisn="'.$product_details['Product']['wisn'].'"
										   and ProductReview.status = "1"',
												'limit' => 24,
												'fields' => array('ProductReview.*') ,
												'order' => 'ProductReview.created Desc'
											  );
										  $ProductReviews = $this->paginate('ProductReview');
										  $product_details['Product']['reviews'] = count($ProductReviews);
										  if(isset($ProductReviews) and ($ProductReviews))
												{
													$x=0;
													foreach($ProductReviews as $ProductReview)
														{
															$user = $this->User->findbyId($ProductReview['ProductReview']['user_id']);
															$ProductReviews[$x]['ProductReview']['user']  = $user['User']; 
															$x++;
														}
														$this->Set('ProductReviews', $ProductReviews);
														
												}
									/*
										* Product reviews End here.
									*/
									/*
										* Product Option  Start here.
									*/
											$ProductOptions = $this->OptionValue->find('all',
											 array('conditions'=>'OptionValue.product_id = '.$product_details['Product']['id'].'',
											 'fields'=>'DISTINCT OptionValue.option_id, OptionValue.value_name')); 
											 
											 
											 $x = 0; 
											 foreach($ProductOptions as $ProductOption)
												{
													$option = $this->Option->findById($ProductOption['OptionValue']['option_id']);
													$exp_value_name = explode('-',$ProductOption['OptionValue']['value_name']);
													$ProductOptionValue =$this->OptionValue->find('all', 
													array('conditions'=>'OptionValue.option_id = '.$ProductOption['OptionValue']['option_id'].' 
													and OptionValue.product_id = '.$product_details['Product']['id'].'',
													'fields'=>'OptionValue.*')); 
													
													//pr($ProductOptionValue);
													//exit;
													$count = count($exp_value_name);
													
													foreach($ProductOptionValue as $val)
														{
															for($i=0; $i<$count; $i++)
															{
																$exp_OptionValue = explode('-',$val['OptionValue']['option_value']);
																$num_cal[''.$exp_value_name[$i].'']['type'] = $option['Option']['type'];
																$num_cal[''.$exp_value_name[$i].'']['name'] = $exp_value_name[$i];
																$num_cal[''.$exp_value_name[$i].'']['options'][] = $exp_OptionValue[$i];
															}
														}
												}
											 		if(isset($num_cal) and ($num_cal))
														{
															$this->Set('options', $num_cal);
														}
									/*
										* Product reviews End here.
									*/
								$this->Set('product_detail', $product_details); 	
								 /***********************************************************************************/
									/*
										* Specification Related to that Product
									*/
											$specifications = $this->Specification->find('all', 
											array('conditions'=>'Specification.product_id="'.$product_details['Product']['id'].'"'));
											if(isset($specifications) and ($specifications))
												{
													//pr($specifications);
													//exit;
													$xc =0;
													foreach($specifications as $specification)
													 {
													   $attribute_key = $this->__get_attr_name($specification['Specification']['attr_id']);
													   // $group_attr = $this->_get_group_attr($attribute_key['Attribute']['attr_gp_id']);
													   $specifications[$xc]['Specification']['key'] = $attribute_key['Attribute']['name']; 
													  // $master_specification[$xc]['AttrGroup']['name'] = $group_attr['AttrGroup']['name'];
													   $master_specification['Specifications']=  $specifications;
													   $xc++;
													 }
													 if(isset($master_specification) and ($master_specification))
														 {
															// pr($master_specification); exit; 
															$this->Set('specifications', $master_specification);
														 }
	
												}
									/*
										* Specification End here.
									*/
								/***********************************************************************************/
							}
						else
							{
								$this->redirect(array('controller'=>'pages', 'action'=>'home'));
							}

					}
					else
					{
						$this->redirect(array('controller'=>'pages', 'action'=>'home'));
					}
		}
	
	
		function __ups_calulate($country_code,$state_code , $Zip_code )
		{
			$ups_settings = $this->UpsShipping->findByid(1);
			$ups_settings_services = $ups_settings['UpsShipping']['services'];
			$ups_settings_services_exp = explode(',',$ups_settings_services);
			if($ups_settings_services_exp):
			foreach($ups_settings_services_exp as $ups_service)
				{
					$Key_Value_array = explode('-',$ups_service);
					$services['ups'][$Key_Value_array[0]] = ''.str_replace('_',' ',$Key_Value_array[1]).'';
				}
			endif;
					/*$services['usps']['EXPRESS'] = 'Express';
					$services['usps']['PRIORITY'] = 'Priority';
					$services['usps']['PARCEL'] = 'Parcel';
					$services['usps']['FIRST CLASS'] = 'First Class';
					$services['usps']['EXPRESS SH'] = 'Express SH';
					$services['usps']['BPM'] = 'BPM';
					$services['usps']['MEDIA '] = 'Media';
					$services['usps']['LIBRARY'] = 'Library';*/
					// FedEx
					$FEDEX_settings = $this->FedexShipping->findByid(1);
					//pr($FEDEX_settings);
					//exit;
					$FEDEX_settings_services = $FEDEX_settings['FedexShipping']['services'];
					$FEDEX_settings_services_exp = explode(',',$FEDEX_settings_services);
					if($FEDEX_settings_services_exp):
					foreach($FEDEX_settings_services_exp as $FEDEX_service)
						{
							$FEDEX_serviceKey_Value_array = explode('-',$FEDEX_service);
							$services['fedex'][$FEDEX_serviceKey_Value_array[0]] = ''.str_replace('_',' ',$FEDEX_serviceKey_Value_array[1]).'';
						}
					endif;
					/*$services['fedex']['PRIORITYOVERNIGHT'] = 'Priority Overnight';
					$services['fedex']['STANDARDOVERNIGHT'] = 'Standard Overnight';
					$services['fedex']['FIRSTOVERNIGHT'] = 'First Overnight';
					$services['fedex']['FEDEX2DAY'] = '2 Day';
					$services['fedex']['FEDEXEXPRESSSAVER'] = 'Express Saver';
					$services['fedex']['FEDEXGROUND'] = 'Ground';
					$services['fedex']['FEDEX1DAYFREIGHT'] = 'Overnight Day Freight';
					$services['fedex']['FEDEX2DAYFREIGHT'] = '2 Day Freight';
					$services['fedex']['FEDEX3DAYFREIGHT'] = '3 Day Freight';
					$services['fedex']['GROUNDHOMEDELIVERY'] = 'Home Delivery';
					$services['fedex']['INTERNATIONALECONOMY'] = 'International Economy';
					$services['fedex']['INTERNATIONALFIRST'] = 'International First';
					$services['fedex']['INTERNATIONALPRIORITY'] = 'International Priority';
					
					
					FedExPackagingType 	Valid Package Types:
					• FEDEXENVELOPE
					• FEDEXPAK
					• FEDEXBOX
					• FEDEXTUBE
					• FEDEX10KGBOX
					• FEDEX25KGBOX
					• YOURPACKAGING (Default)
					*/
					
					$FlateRate_settings = $this->FlateRate->findByid(1);
				
					$l_w_h = explode('*',"".$ups_settings['UpsShipping']['dimensions']."");
					$ups_picup = explode('-',"".$ups_settings['UpsShipping']['pickup_method']."");
					$packaging_type = explode('_',"".$ups_settings['UpsShipping']['packaging_type']."");
					//pr($ups_picup);
					//exit;
					$config = array(
					// Services
					'services' => $services,
					
					'pickup_method' => "".$ups_picup[0]."",
					
					'packaging_type' => "".$packaging_type[0]."",
					
					'length_code' => "".$ups_settings['UpsShipping']['length_code']."",
					
					'weight_code' => "".$ups_settings['UpsShipping']['weight_code']."",
					
					'CustomerTransactionIdentifier' => "".$FEDEX_settings['FedexShipping']['CustomerTransactionIdentifier']."",  // For feedex
					
					'DropoffType' => "".$FEDEX_settings['FedexShipping']['DropoffType']."",// For feedex
					
					'CarrierCode' => "".$FEDEX_settings['FedexShipping']['CarrierCode']."",// For feedex
					
					'PayorType' => "".$FEDEX_settings['FedexShipping']['PayorType']."",// For feedex
					
					'PackageCount' => "".$FEDEX_settings['FedexShipping']['PackageCount']."",// For feedex
					
					'FedexPackaging ' => "".$FEDEX_settings['FedexShipping']['Packaging']."",// For feedex
					// Weight
					'weight' => 2, // Default = 1
					'weight_units' => ''.$ups_settings['UpsShipping']['weight_code'].'', // lb (default), oz, gram, kg
					// Size
					'size_length' => $l_w_h[0], // Default = 8
					'size_width' =>  $l_w_h[1], // Default = 4
					'size_height' => $l_w_h[2], // Default = 2
					'size_units' => ''.$ups_settings['UpsShipping']['length_code'].'', // in (default), feet, cm
					// From
					'from_zip' => 97210, 
					'from_state' => "OR", // Only Required for FedEx
					'from_country' => "US",
					// To
					'to_zip' => $Zip_code,
					'to_state' => "".$state_code."",
					'to_country' => "".$country_code."",  // Enter BY User(Or Customer From FRont End)
					// Service Logins
					'ups_access' => ''.$ups_settings['UpsShipping']['access_key'].'', // UPS Access License Key
					'ups_user' => ''.$ups_settings['UpsShipping']['username'].'', // UPS Username  
					'ups_pass' => ''.$ups_settings['UpsShipping']['password'].'', // UPS Password  
					'ups_account' => ''.$ups_settings['UpsShipping']['account_no'].'', // UPS Account Number
					//'usps_user' => '229DARKW7858', // USPS User Name
					'fedex_account' => ''.$FEDEX_settings['FedexShipping']['fedex_account'].'', // FedEX Account Number
					'fedex_meter' => ''.$FEDEX_settings['FedexShipping']['fedex_meter'].'' // FedEx Meter Number 
					
				);
				//pr($config);
				//exit;
				App::import('Vendor', 'shipping/shipping_calculator');
				// Create Class (with config array)
				$ship = new ShippingCalculator($config);
				// Get Rates
				//pr($ups_rates);
				//exit;
				$ups_rates = $ship->calculate();
				//$codes = array_keys($ups_rates['ups']);
				//$ship = new ShippingCalculator ($config);
				//$rates = $ship->calculate('usps','FIRST CLASS');
				
				// Print Array of Rates
				//print "
				//Rates for sending a ".$config['weight']." ".$config['weight_units'].", 
				//".$config['size_length']." x ".$config['size_width']." x ".$config['size_height']."
				// ".$config['size_units']." package from ".$config['from_zip']." to ".$config['to_zip'].":
				//<xmp>";
				//print_r($ups_rates);
				//print_r($codes);
				//print "</xmp>";
			
				if(isset($ups_rates) and $ups_rates)
					{
						if(isset($ups_rates['fedex']) and ($ups_rates['fedex']))
							{
								$x_1=0;
								foreach($ups_rates['fedex'] as $key=>$value)
									{
										$rate_analysys['fedex'][$x_1]['ServiceName'] = $this->_get_fedex_service_name($key); 
										$rate_analysys['fedex'][$x_1]['ServiceCode'] = $key; 
										$rate_analysys['fedex'][$x_1]['Rate'] = $value; 
										$x_1++;
									}
							}
						if(isset($ups_rates['ups']) and ($ups_rates['ups']))
							{
								$x=0;
								foreach($ups_rates['ups'] as $key=>$value)
									{
										$rate_analysys['ups'][$x]['ServiceName'] = $this->_get_ups_service_name($key); 
										$rate_analysys['ups'][$x]['ServiceCode'] = $key; 
										$rate_analysys['ups'][$x]['Rate'] = $value; 
										$x++;
									}
							}
						if(isset($FlateRate_settings['FlateRate']['cost']) and ($FlateRate_settings['FlateRate']['cost']))
							{
								$rate_analysys['Flaterate'][0]['ServiceName'] = "Flate Rate";
								$rate_analysys['Flaterate'][0]['ServiceCode'] = "Flate_Rate";
								$rate_analysys['Flaterate'][0]['Rate'] = $FlateRate_settings['FlateRate']['cost'];
							}
							
							if(isset($rate_analysys) and ($rate_analysys)):
								return $rate_analysys;
							endif;
					}
		}


	
	function cart($action="",$product_slug="", $seller_token="")
		{
			$countries = $this->__List_code_countries();
			$this->Set('countries',$countries);
			$states = $this->__List_code_states();
			$this->Set('states',$states);
			if(isset($seller_token) and ($seller_token))
				{
					$seller = $this->Seller->findByMerchantToken($seller_token);
					$seller_id = $seller['Seller']['id'];
				}
			   switch($action)
				 {
						case "add":
							if(isset($product_slug) and ($product_slug))
							{       
								$exp_product_slug = explode("^", $product_slug);
								if(isset($exp_product_slug[0]) and ($exp_product_slug[0]))
									{
										$product_slug = $exp_product_slug[0];
										if(isset($exp_product_slug[1]) and ($exp_product_slug[1])){
										            $up_quantity_1 = $exp_product_slug[1];
										}else{
											$up_quantity_1 = 1; 
										}
									}
									else
										{
											$product_slug = $product_slug;
											
										}
									$product_id = $this->__get_slug_to__id($product_slug,"Product");
									$current_cart = $this->Session->read('cart');
									if(isset($current_cart['product_id']) and ($current_cart['product_id']))
										{
												  $already_exist = array_key_exists($product_id, $current_cart['product_id']);
												  if(isset($already_exist) and ($already_exist))
														{
															//echo "Item Already in Cart! check Your Cart<br>";
														if(isset($up_quantity_1) and ($up_quantity_1))
															{
																$new_quantity = $up_quantity_1; 
															}
														else
															{
																$new_quantity = $current_cart['product_id'][$product_id]['Cart_quantity']+1;
															}
															$new_price =
															$new_quantity * $current_cart['product_id'][$product_id]['product_price'] ;
															$current_cart['product_id'][$product_id]['id'] = $current_cart['product_id'][$product_id]['id']; 
															$current_cart['product_id'][$product_id]['Cart_price'] =$new_price; 
															$current_cart['product_id'][$product_id]['Cart_quantity'] = $new_quantity; 
															$current_cart['product_id'][$product_id]['product_price']  = 
															$current_cart['product_id'][$product_id]['product_price'] ;
															$new_price_repeat = $current_cart['total_price']
																		+$current_cart['product_id'][$product_id]['product_price'];
															$this->Session->write('cart.product_id.'.$product_id,$current_cart['product_id'][$product_id]);
															$this->Session->write('cart.total_price',$new_price_repeat);
														}
													else
														{
															$product_details = $this->Product->findById($product_id, 
																								  array('fields'=>'Product.*
																				'));
															if(isset($seller_id) and ($seller_id))
																{
													$MasterProduct = $this->__get_product_seller_price($product_details['Product']['id'], $seller_id);
																}
															else
																{
													$MasterProduct = $this->__get_product_min_price($product_details['Product']['id']);
																}
															$product_details['Product']['price'] = $MasterProduct['price'];
															$product_details['Product']['seller_id'] = $MasterProduct['seller_id'];
															$stock_detail = $this->_get_stock_position($product_details['Product']['stock']);
															$product_details['Product']['stock_detail']= $stock_detail;
														if(isset($product_details['Product']['stock']) and ($product_details['Product']['stock']=="2"))
															{
															if(isset($MasterProduct['qty']) and ($MasterProduct['qty']>0))
																{   
																$ProductCart['ProductCart']['id'] = $product_details['Product']['id'];
																$ProductCart['ProductCart']['Cart_quantity'] = 1; // It will come dynamicaly 
																$ProductCart['ProductCart']['Cart_price'] =
																($ProductCart['ProductCart']['Cart_quantity']*$product_details['Product']['price']);
																$ProductCart['ProductCart']['product_price'] = $product_details['Product']['price'];
																$current_count = count($current_cart['product_id']);
																$current_cart['product_id'][$ProductCart['ProductCart']['id']] =
																$ProductCart['ProductCart'];
																$new_price = $current_cart['total_price']
																+$ProductCart['ProductCart']['product_price'];
																$this->Session->write('cart.product_id',$current_cart['product_id']);
																$this->Session->write('cart.total_price',$new_price);
																}
															}
														}
										}
										else
										{
										//echo "else";
										$product_details = $this->Product->findById($product_id, 
																  array('fields'=>'Product.*
										'));

										
												if(isset($seller_id) and ($seller_id))
													{
										$MasterProduct = $this->__get_product_seller_price($product_details['Product']['id'], $seller_id);
													}
												else
													{
										$MasterProduct = $this->__get_product_min_price($product_details['Product']['id']);
													}
										$product_details['Product']['price'] = $MasterProduct['price'];
										$product_details['Product']['seller_id'] = $MasterProduct['seller_id'];
										$stock_detail = $this->_get_stock_position($product_details['Product']['stock']);
										$product_details['Product']['stock_detail']= $stock_detail;
										if(isset($product_details['Product']['stock']) and ($product_details['Product']['stock']=="2"))
											{
											if(isset($MasterProduct['qty']) and ($MasterProduct['qty']>0))
												{  
												 //pr($product_details);
												 //exit;
													$ProductCart['ProductCart']['id'] = $product_details['Product']['id']; 
													$ProductCart['ProductCart']['Cart_quantity'] = 1; // It will come dynamicaly 
													$ProductCart['ProductCart']['Cart_price'] =
													($ProductCart['ProductCart']['Cart_quantity']*$product_details['Product']['price']);
													$ProductCart['ProductCart']['product_price'] = $product_details['Product']['price'];
													$current_cart['product_id'][$ProductCart['ProductCart']['id']] = $ProductCart['ProductCart'];
													$this->Session->write('cart.product_id',$current_cart['product_id']);
													$this->Session->write('cart.total_price',$ProductCart['ProductCart']['Cart_price']);
												}
											}
										}
										$current_cart = $this->Session->read('cart');
										if(isset($current_cart) and sizeof($current_cart))
											{
												$total_sum = 0;
												foreach($current_cart['product_id'] as $cart)
													{
														$total_sum = $total_sum + $cart['Cart_price'];
													}
												$this->Session->write('cart.total_price',$total_sum);
												$current_cart_final = $this->Session->read('cart');
												$x=0;
										foreach($current_cart_final['product_id'] as $cart)
											{
												$product_details = $this->Product->findById($cart['id']);
												if(isset($seller_id) and ($seller_id))
													{
										$MasterProduct = $this->__get_product_seller_price($product_details['Product']['id'], $seller_id);
													}
												else
													{
										$MasterProduct = $this->__get_product_min_price($product_details['Product']['id']);
													}
												$product_details['Product']['price'] = $MasterProduct['price'];
												$product_details['Product']['seller_id'] = $MasterProduct['seller_id'];
												$stock_detail = $this->_get_stock_position($product_details['Product']['stock']);
												$product_details['Product']['stock_detail']= $stock_detail; 
												$current_cart_final['product_id'][$cart['id']]['Product'] = $product_details['Product']; 
												$this->Session->write('cart.product_id.'.$cart['id'].'.Product',
												$current_cart_final['product_id'][$cart['id']]['Product']);
												$x++;
											}
										$this->redirect(array('controller'=>'products', 'action'=>'cart', 'view'));
									}
							}
							break;
						case "delete":
							$current_cart = $this->Session->read('cart');
						    //pr($current_cart);
							//exit;
							$product_id = $this->__get_slug_to__id($product_slug,"Product");
							if(isset($product_id) and ($product_id))
								{
									if(isset($current_cart['product_id'][$product_id]) and ($current_cart['product_id'][$product_id]))
										{
											$item_price = $current_cart['product_id'][$product_id]['Cart_price'];
											$total_cart_price = $current_cart['total_price']; 
											$now_total = $total_cart_price-$item_price;
											$this->Session->delete('cart.product_id.'.$product_id);
											$this->Session->write('cart.total_price',$now_total); 
											$this->redirect(array('controller'=>'products', 'action'=>'cart', 'view'));
										}
								}
								else
								{
									$this->redirect(array('controller'=>'products', 'action'=>'cart', 'view'));
								}
								
						break;
						default:
								if(isset($this->data['Shipping']) and ($this->data['Shipping']))
									{
										$country_code = $this->data['Shipping']['country'];
										$state_code = $this->data['Shipping']['state'];
										$Zip_code = $this->data['Shipping']['Zip'];
										$rate_analysys = $this->__ups_calulate($country_code,$state_code , $Zip_code );
										$this->Set('rate_analysys', $rate_analysys);
									}
						   $current_cart = $this->Session->read('cart');
						   $this->Set('current_cart', $current_cart);
						break;
				 }
		}
		
		function product_review()
			{
				if(isset($this->data))
					{
					  if(isset($this->data['ProductReview']) and ($this->data['ProductReview']))
							{
								$this->data['ProductReview']['product_id'] =  $this->__get_product_id_from_wisn($this->data['ProductReview']['wisn']);
								$this->data['ProductReview']['user_id'] = $this->Auth->User('id');
								$ip = $this->RequestHandler->getClientIp();
								$this->data['ProductReview']['ip'] = $ip;
								$this->ProductReview->Save($this->data['ProductReview']);
								$this->Session->setFlash('Product review has been submitted.');
								$this->redirect(array('action'=>'product',$this->data['ProductReview']['slug']));
							}
					}
					else
					{
						$this->redirect(array('/'));
					}
			}
			
		function offer_listing($product_wisn, $tab_condition)
			{
					$product_details = $this->Product->findByWisn($product_wisn);
					if(isset($product_details) and ($product_details))
						{
							$category = $this->Category->findById($product_details['Product']['cat_id']);
							$product_details['Product']['category']= $category['Category']; 
							$stock_detail = $this->_get_stock_position($product_details['Product']['stock']);
							$product_details['Product']['stock_detail']= $stock_detail; 
							$MasterProduct = $this->__get_product_min_price($product_details['Product']['id']);
							$seller = $this->_get_seller($MasterProduct['seller_id']); 
							$MasterProduct['Seller'] = $seller['Seller']; 
							$product_details['Product']['MasterProduct']= $MasterProduct;
							$brand_name = $this->_get_brand_name($product_details['Product']['brand_id']);
							$product_details['Product']['Brand'] = $brand_name; 
							$ratings = $this->__get_product_rating($product_details['Product']['wisn']);
							$product_details['Product']['rating'] = $ratings;
							$this->Set('product_detail', $product_details); 
							$new_MasterProduct = $this->_product_condition_price_min($product_details['Product']['id'], 'new');
							if(isset($new_MasterProduct[0][0]['Price']) and ($new_MasterProduct[0][0]['Price']))
								{
									$price_list[1]['name'] = "new";
									$price_list[1]['new'] = $new_MasterProduct[0][0]['Price'];
								}
							$Used_MasterProduct = $this->_product_condition_price_min($product_details['Product']['id'], 'Used');
							if(isset($Used_MasterProduct[0][0]['Price']) and ($Used_MasterProduct[0][0]['Price']))
								{
									$price_list[2]['name'] = "Used";
									$price_list[2]['Used'] = $Used_MasterProduct[0][0]['Price'];
								}
							$Refurbished_MasterProduct = $this->_product_condition_price_min($product_details['Product']['id'], 'Refurbished');
							//pr($Refurbished_MasterProduct);
							//exit;
							if(isset($Refurbished_MasterProduct[0][0]['Price']) and ($Refurbished_MasterProduct[0][0]['Price']))
								{
									$price_list[3]['name'] = "Refurbished";
									$price_list[3]['Refurbished'] = $Refurbished_MasterProduct[0][0]['Price'];
								}
							$Collectible_MasterProduct = $this->_product_condition_price_min($product_details['Product']['id'], 'Collectible');
							if(isset($Collectible_MasterProduct[0][0]['Price']) and ($Collectible_MasterProduct[0][0]['Price']))
								{
									$price_list[5]['name'] = "Collectible";
									$price_list[5]['Collectible'] = $Collectible_MasterProduct[0][0]['Price'];
								}
							//pr($price_list);
							//exit;	
							$this->Set('price_list', $price_list);
							
							//pr($product_details['Product']['id']);
							//exit;
								
							$new_price_list = $this->__new_price_offer_list($product_details['Product']['id']);	
							$used_price_list = $this->__used_price_offer_list($product_details['Product']['id']);
							$Collectible_price_list = $this->__Collectible_price_offer_list($product_details['Product']['id']);	
							$Refurbished_price_list = $this->__Refurbished_price_offer_list($product_details['Product']['id']);	
							//pr($Refurbished_price_list);
							//exit;	
							$offer_list = array();
							
							if(isset($new_price_list) and ($new_price_list))
								{
									$x =0;
									foreach($new_price_list as $new_price)
										{
											$cond = $this->_get_product_condition($new_price['MasterProduct']['conditions']);
											$new_price_list[$x]['MasterProduct']['cond'] =$cond['name'];
											$x++;
										}
									$offer_list[1]['name'] = 'new';	
									$offer_list[1]['new'] = $new_price_list;
								}
							if(isset($used_price_list) and ($used_price_list))
								{
									
									$x1 =0;
									foreach($used_price_list as $used_price)
										{
											$cond = $this->_get_product_condition($used_price['MasterProduct']['conditions']);
											$used_price_list[$x1]['MasterProduct']['cond'] =$cond['name'];
											$x1++;
										}
									$offer_list[2]['name'] = 'Used';		
									$offer_list[2]['Used'] = $used_price_list;
								}
							if(isset($Collectible_price_list) and ($Collectible_price_list))
								{
									$x11 =0;
									foreach($Collectible_price_list as $Collectible_price)
										{
											$cond = $this->_get_product_condition($Collectible_price['MasterProduct']['conditions']);
											$Collectible_price_list[$x11]['MasterProduct']['cond'] =$cond['name'];
											$x11++;
										}
									$offer_list[3]['name'] = 'Collectible';		
									$offer_list[3]['Collectible'] =$Collectible_price_list;
								}
							if(isset($Refurbished_price_list) and ($Refurbished_price_list))
								{
									$x111 =0;
									foreach($Refurbished_price_list as $Refurbished_price)
										{
											$cond = $this->_get_product_condition($Refurbished_price['MasterProduct']['conditions']);
											$Refurbished_price_list[$x111]['MasterProduct']['cond'] =$cond['name'];
											$x111++;
										}
									$offer_list[4]['name'] = 'Refurbished';			
									$offer_list[4]['Refurbished'] = $Refurbished_price_list;
								}
							$this->set('offer_list', $offer_list); 
						}
			}
			
		function search()
			{
				if(isset($this->data) and ($this->data))
					{
						if(isset($this->data['Category']) and ($this->data['Category']))
							{
								if(isset($this->data['Category']['id']) and ($this->data['Category']['id']==0))
									{
										$operator = "or";
									}
								else
									{
										$operator = "and";
									}
								$this->paginate['Product'] =array('conditions' =>
								'(Product.parent_cat_id Like "%'.$this->data['Category']['id'].'%" and Product.status="1" )
								'.$operator.'
								(
									Product.wisn Like "%'.$this->data['Category']['search'].'%" 
									or Product.name Like "%'.$this->data['Category']['search'].'%" 
									or Product.p_model Like "%'.$this->data['Category']['search'].'%" 
									or Product.upc Like "%'.$this->data['Category']['search'].'%" 
									or Product.description Like "%'.$this->data['Category']['search'].'%" 
									or Product.hash Like "%'.$this->data['Category']['search'].'%" 
									or Product.manufacturer Like "%'.$this->data['Category']['search'].'%"
								)',
								'limit' => 24,
								'fields' => array('Product.*') ,
								'order' => 'Product.created Desc'
								);
								$products = $this->paginate('Product');
				                if(isset($products) and ($products))
									{
										$x =0;
										foreach($products as $product)
											{
												$ratings = $this->__get_product_rating($product['Product']['wisn']);
												$products[$x]['Product']['rating'] = $ratings;
												$stock_detail = $this->_get_stock_position($product['Product']['stock']);
												$products[$x]['Product']['stock_detail']= $stock_detail; 
												$MasterProduct = $this->__get_product_min_price($product['Product']['id']);
												if(isset($MasterProduct) and ($MasterProduct))
													{
														$product_condition  = $this->_get_product_condition($MasterProduct['conditions']);
														$products[$x]['Product']['condition'] = $product_condition;
														$products[$x]['Product']['MasterProduct'] = $MasterProduct;
													}
												else
													{
														unset($products[$x]);
													}
												$x++;
											}
										$this->Set('total_products', count($products)); 
										$this->Set('products', $products);
									}
							}
					}
			}
			
			
			
			
	function advancesearch()
		{
		}
	
	function advancesearchresults()
		{
			if(isset($this->data) and ($this->data))
				{
						if(isset($this->data['Search']) and ($this->data['Search']))
							{
								if(isset($this->data['Search']['anyword']) and ($this->data['Search']['anyword']))
									{
										if(isset($this->data['Search']['cat_id']) and ($this->data['Search']['cat_id']))
											{
												$operator = "or";
											}
										else
											{
												$operator = "and";
											}
										$conditions = '(Product.parent_cat_id Like "%'.$this->data['Search']['cat_id'].'%" )
											'.$operator.'
											(
												Product.wisn Like "%'.$this->data['Search']['keyword'].'%" 
												or Product.name Like "%'.$this->data['Search']['keyword'].'%" 
											)
											
											';
										$conditions = "(".$conditions.") and (Product.status='1')";	
										if(isset($this->data['Search']['seller']) and ($this->data['Search']['seller']))
											{
												$conditions = $conditions.' or Product.manufacturer Like "%'.$this->data['Search']['keyword'].'%" '; 
											}
											
									}
								elseif(isset($this->data['Search']['allwords']) and ($this->data['Search']['allwords']))
									{
										if(isset($this->data['Search']['cat_id']) and ($this->data['Category']['cat_id']))
											{
												$operator = "or";
											}
										else
											{
												$operator = "and";
											}
										$conditions = '(Product.parent_cat_id Like "%'.$this->data['Search']['cat_id'].'%" )
											'.$operator.'
											(
												Product.wisn Like "%'.$this->data['Search']['keyword'].'%" 
												or Product.name Like "%'.$this->data['Search']['keyword'].'%" 
											)
											
											';
										$conditions = "(".$conditions.") and (Product.status='1')";	
											if(isset($this->data['Search']['seller']) and ($this->data['Search']['seller']))
												{
													$conditions = $conditions.' or Product.manufacturer Like "%'.$this->data['Search']['keyword'].'%" '; 
												}
												
									}else{
										$conditions = "Product.status='1'";
									}
								
								
									//echo$conditions;
									//exit;
								$this->paginate['Product'] =array('conditions' =>
								''.$conditions.'',
								'limit' => 24,
								'fields' => array('Product.*') ,
								'order' => 'Product.created Desc'
								);
								$products = $this->paginate('Product');
				                if(isset($products) and ($products))
									{
										$x =0;
										foreach($products as $product)
											{
												$ratings = $this->__get_product_rating($product['Product']['wisn']);
												$products[$x]['Product']['rating'] = $ratings;
												$stock_detail = $this->_get_stock_position($product['Product']['stock']);
												$products[$x]['Product']['stock_detail']= $stock_detail; 
												$MasterProduct = $this->__get_product_min_price($product['Product']['id']);
												if(isset($MasterProduct) and ($MasterProduct))
													{
														$product_condition  = $this->_get_product_condition($MasterProduct['conditions']);
														$products[$x]['Product']['condition'] = $product_condition;
														$products[$x]['Product']['MasterProduct'] = $MasterProduct;
													}
												else
													{
														unset($products[$x]);
													}
												$x++;
											}
										$this->Set('total_products', count($products)); 
										$this->Set('products', $products);
									}
							}
					
				}
		}
		
	function MyWishlist()
		{
			$slug = $this->Auth->User('slug'); 
			$user = $this->User->findBySlug($slug, array('fields'=>'User.*'));
			$this->Set('user',$user);
			$user_id = $user['User']['id'];
			$user_wish_listes = $this->Wishlist->find('all', array('conditions'=>'Wishlist.user_id="'.$user_id.'"', 
			'fields'=>'Wishlist.name,Wishlist.id, Wishlist.hash '));
			//pr($user_wish_listes);
			//exit;
			if(isset($user_wish_listes) and ($user_wish_listes))
				{
					$x=0	;
					foreach($user_wish_listes as $user_wish_list)
						{
							$this->paginate['WishlistProduct'] =
							array('conditions' => 'WishlistProduct.wishlist_id="'.$user_wish_list['Wishlist']['id'].'"',
											'fields' => array('WishlistProduct.product_id,WishlistProduct.id') ,
											'order' => 'WishlistProduct.created Desc'
										  );  
							$WishlistProducts = $this->paginate('WishlistProduct');
							if(isset($WishlistProducts) and ($WishlistProducts))
								{
									$vb=0;
									foreach($WishlistProducts as $WishlistProduct)
									   {
											$get_product = $this->wisn_product($WishlistProduct['WishlistProduct']['product_id']);
											$WishlistProducts[$vb]['WishlistProduct']['Product'] = $get_product['Product'];
											$vb++;
										}
							   }
							$user_wish_listes[$x]['Wishlist']['Products'] = $WishlistProducts;
							$x++;
						}
						//pr($user_wish_listes);
						//exit;
						$this->Set('user_wish_listes', $user_wish_listes);
				}
			//exit;
			
		}
			
	function add_to_wishlist($product_slug="")
		{
				$params = $this->params;
				$user_id = $this->Auth->User('id');
				$wishlist = $this->Wishlist->find('count',  array('conditions'=>'Wishlist.user_id="'.$user_id.'"', 'fields'=>'Wishlist.id'));
				if(isset($wishlist) and ($wishlist==1))
					{
						$wishlist = $this->Wishlist->find('all',  array('conditions'=>'Wishlist.user_id="'.$user_id.'"', 
						'fields'=>'Wishlist.id, Wishlist.hash'));
				   		if(isset($product_slug) and ($product_slug))
							  {
								$product_details = $this->Product->findBySlug($product_slug,array('fields'=>'Product.id, Product.wisn'));
								$this->data['WishlistProduct']['wishlist_id'] = $wishlist[0]['Wishlist']['id'];
								$this->data['WishlistProduct']['product_id'] = $product_details['Product']['id'];
								$this->data['WishlistProduct']['wisn'] = $product_details['Product']['wisn'];
								if(isset($this->data['WishlistProduct']))
									{
										$this->WishlistProduct->Save($this->data['WishlistProduct']);
										$this->redirect(array('action'=>'MyWishlist')); 
									}
							  }
					}
					elseif($wishlist>1)
						{
							$this->set('wishlist_option', 'select');
							$wishlist_list = $this->Wishlist->find('all',  array('conditions'=>'Wishlist.user_id="'.$user_id.'"',
							'fields'=>'Wishlist.name,Wishlist.id, Wishlist.access','Wishlist.hash'));
							$this->set('wishlist_list', $wishlist_list);
							if(isset($product_slug) and ($product_slug))
								  {
									$product_details = $this->Product->findBySlug($product_slug,array('fields'=>'Product.id, Product.wisn'));
									//pr($product_details);
									//exit;
									$this->data['WishlistProduct']['product_id'] = $product_details['Product']['id'];
									$this->data['WishlistProduct']['wisn'] = $product_details['Product']['wisn'];
									if(isset($this->data['WishlistProduct']))
										{
											$this->set('WishlistProduct', $this->data['WishlistProduct']);
										}
								  }
						}
					else
						{
							$this->set('wishlist_option', 'new');
							$user_id = $this->Auth->User('id');
							$address = $this->Address->find('all', array('conditions'=>'Address.user_id="'.$user_id.'"')); 
							foreach($address as $addres)
								{
									unset($addres['Address']['user_id']);
									unset($addres['Address']['country']);
									unset($addres['Address']['status']);
									unset($addres['Address']['created']);
									unset($addres['Address']['active']);
									$huk_address[$addres['Address']['id']] = implode(', ',$addres['Address']);
								}
							$this->Set('huk_address', $huk_address);
							$__list_countries = $this->__list_countries();
							$this->Set('list_countries', $__list_countries);
	
							if(isset($product_slug) and ($product_slug))
								  {
									$product_details = $this->Product->findBySlug($product_slug, array('fields'=>'Product.id, Product.wisn'));
									$this->data['WishlistProduct']['product_id'] = $product_details['Product']['id'];
									$this->data['WishlistProduct']['wisn'] = $product_details['Product']['wisn'];
									if(isset($this->data['WishlistProduct']))
										{
											$this->set('WishlistProduct', $this->data['WishlistProduct']);
										}
								  }
						}
					
					if(isset($params['named']['func']) and ($params['named']['func']=="create"))
						{
							$this->set('wishlist_option', 'new');
							$user_id = $this->Auth->User('id');
							$address = $this->Address->find('all', array('Address.user_id="'.$user_id.'"')); 
							foreach($address as $addres)
								{
									unset($addres['Address']['user_id']);
									unset($addres['Address']['country']);
									unset($addres['Address']['status']);
									unset($addres['Address']['created']);
									unset($addres['Address']['active']);
									$huk_address[$addres['Address']['id']] = implode(', ',$addres['Address']);
								}
							$this->Set('huk_address', $huk_address);
							$__list_countries = $this->__list_countries();
							$this->Set('list_countries', $__list_countries);
	
						}
					elseif(isset($params['named']['func']) and ($params['named']['func']=="editwishlist"))
						{
							$this->set('wishlist_option', 'new');
							$user_id = $this->Auth->User('id');
							$address = $this->Address->find('all', array('conditions'=>'Address.user_id="'.$user_id.'"')); 
							//pr($address);
							//exit;

							foreach($address as $addres)
								{
									unset($addres['Address']['user_id']);
									unset($addres['Address']['country']);
									unset($addres['Address']['status']);
									unset($addres['Address']['created']);
									unset($addres['Address']['active']);
									$huk_address[$addres['Address']['id']] = implode(', ',$addres['Address']);
								}
							$this->Set('huk_address', $huk_address);
							$__list_countries = $this->__list_countries();
							$this->Set('list_countries', $__list_countries);
							if(isset($params['named']['hash']) and ($params['named']['hash']))
								{
									$editable_wish_list = $this->Wishlist->findByHash($params['named']['hash']);
									$this->Set('editable_wish_list', $editable_wish_list);
								}
								else
								{
									$this->redirect(array('action'=>'MyWishlist')); 
								}
							
						}
						
						
						
					if(isset($this->data['New']) and ($this->data['New']))
						{
							if(isset($this->data['New']['Wishlist']) and ($this->data['New']['Wishlist']))
								{
									if(isset($this->data['New']['Wishlist']['address']) and ($this->data['New']['Wishlist']['address']==0))
										{
											$this->data['New']['Wishlist']['address_id'] = 0;
										}
									elseif(isset($this->data['New']['Wishlist']['address']) and ($this->data['New']['Wishlist']['address']==1))
										{
											$this->data['New']['Wishlist']['address_id'] = $this->data['New']['Wishlist']['address_id'];
										}
									elseif(isset($this->data['New']['Wishlist']['address']) and ($this->data['New']['Wishlist']['address']==2))
										{
											if(isset($this->data['New']['Address']) and sizeof($this->data['New']['Address']))
												{
													$this->data['New']['Address']['user_id'] = $this->Auth->User('id');
													$this->Address->Save($this->data['New']['Address']);
													$Addressinsert_id = $this->Address->getLastinsertId();
													$this->data['New']['Wishlist']['address_id'] = $Addressinsert_id;
												}
										}
									$this->data['New']['Wishlist']['birthday'] = 
									date('Y').'-'.$this->data['New']['Wishlist']['month'].'-'.$this->data['New']['Wishlist']['day'];
									$this->data['New']['Wishlist']['user_id'] = $this->Auth->User('id');
									$this->data['New']['Wishlist']['hash'] = $this->__generateKey('Wishlist');
									
									$this->Wishlist->Save($this->data['New']['Wishlist']);
									$insert_id = $this->Wishlist->getLastinsertId();
									if(isset($insert_id) and ($insert_id))
											{
												if(isset($this->data['New']['WishlistProduct']) and ($this->data['New']['WishlistProduct']))
													{
														$this->data['New']['WishlistProduct']['wishlist_id'] = $insert_id;
														$product_already_in_list = $this->WishlistProduct->find('first', 
														array('WishlistProduct.wishlist_id='.$this->data['New']['WishlistProduct']['wishlist_id'].' 
														and WishlistProduct.product_id ='.$this->data['New']['WishlistProduct']['product_id'].''));
														if($product_already_in_list and ($product_already_in_list)){
															$this->Session->setFlash('The Product is already in List.');
														}
														else
															{
																$this->WishlistProduct->Save($this->data['New']['WishlistProduct']);
														}
													}
													$this->redirect(array('action'=>'MyWishlist')); 
											}
										else
											{
																						{
												$this->redirect(array('action'=>'MyWishlist')); 
											}

										}
								}
						}
						
					if(isset($this->data['Existing']) and ($this->data['Existing']))
						{
							//pr($this->data['Existing']);
							//exit;
							if(isset($this->data['Existing']['WishlistProduct']) and ($this->data['Existing']['WishlistProduct']))
								{
									$product_already_in_list = $this->WishlistProduct->find('first', 
									array('conditions'=>'WishlistProduct.wishlist_id='.$this->data['Existing']['WishlistProduct']['wishlist_id'].' 
									and WishlistProduct.product_id ='.$this->data['Existing']['WishlistProduct']['product_id'].''));
									if($product_already_in_list and ($product_already_in_list)){
										$this->Session->setFlash('The Product is already in List.');
									}
									else{
										$this->WishlistProduct->Save($this->data['Existing']['WishlistProduct']);
									}
								}
								$this->redirect(array('action'=>'MyWishlist')); 
						}
		}
		
		
	function delete($model, $id_dec, $action)
		{	$id = base64_decode($id_dec);
			if ($this->$model->delete($id))
					{
						if($model=='WishlistProduct')
							{
							}
						elseif($model=='Wishlist')
							{
								$this -> WishlistProduct -> deleteAll(array('WishlistProduct.wishlist_id' => $id));
							}
						$this->Session->setFlash('The '.$model.' item has been deleted.');
						$this->redirect(array('controller'=>'products', 'action' => $action,));
					}
		}
		
	function checkout()
		{
			$__list_countries = $this->__list_countries();
			$this->Set('list_countries', $__list_countries);
			$user_id = $this->Auth->User('id');
			$address = $this->Address->find('all', array('conditions'=>'Address.user_id='.$user_id.''));
			$this->Set('address', $address);
			if(isset($this->data['Address']) and ($this->data['Address']))
				{
					$this->data['Address']['user_id'] =  $this->Auth->User('id');
					$this->Address->Save($this->data['Address']);
					$address_id = $this->Address->getLastinsertId();
					$this->redirect(array('controller'=>'paypals', 'action'=>'ProceedPay',"address"=>base64_encode($address_id)));
				}

		}
		
}
